#include "videodetect.h"
#include "ui_videodetect.h"
#include <QDebug>

using namespace std;
using namespace cv;

CascadeClassifier cascade;

videoDetect::videoDetect(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::videoDetect)
{
    ui->setupUi(this);
    connect(ui->back,&QPushButton::clicked,[=](){
        emit this->back();
    });
}

videoDetect::~videoDetect()
{
    delete ui;
}

void videoDetect::on_show_clicked()
{
    //调用摄像头期间不能上传图像，以防出错
    ui->photo->setEnabled(false);

    //调用摄像头
    VideoCapture video;
    video.open(0);

    stop = false;

    //检测摄像头是否成功打开
    if (!video.isOpened()) {
        qDebug() << "摄像头加载出错！";
        exit(-1);
    }

    /*已训练的人脸识别算法，具体路径需要根据opencv库安装位置在config.h更改*/
    const string casPath = HAAR_PATH;

    //检测是否成功加载级联分类器
    if (!cascade.load(casPath)) {
        qDebug() << "算法加载失败！";
        exit(-1);
    }

    ui->origin->setScaledContents(true);

    while (stop != true) {
        Mat vClip;
        video >> vClip;  //视频转为图像

        //若突然没有视频信号则结束
        if (vClip.empty()) {
            break;
        }

        //灰度化，减少计算
        Mat imgGray;
        cvtColor(vClip, imgGray, COLOR_BGR2GRAY);

        vector<Rect> faces(0);
        cascade.detectMultiScale(imgGray, faces, 1.1, 2, 0, Size(30, 30));  //调用人脸识别算法

        QString sNum = QString::number(faces.size());
        ui->numShow->setText(sNum); //实时输出人脸数

        if (faces.size() > 0) {
            for (size_t i = 0; i < faces.size(); i++) {
                rectangle(vClip, faces[i], Scalar(0, 0, 255), 2, 8, 0);  //生成矩形框出人脸
            }
        }

        Mat temp;
        cvtColor(vClip,temp,COLOR_BGR2RGB);//BGR转化为RGB
        QImage Qtemp = QImage((const unsigned char*)(temp.data),
                                temp.cols, temp.rows, temp.step,
                                QImage::Format_RGB888);

        ui->origin->setPixmap(QPixmap::fromImage(Qtemp));  //输出检测后带框的人脸

        waitKey(1); //waitkey 1ms的延迟
        QApplication::processEvents();


    }


}



void videoDetect::on_photo_clicked()
{

    QString photoName = QFileDialog::getOpenFileName(
                    this,
                    "Select a image",
                    "",
                    "Images(*.png *.xpm *.jpg)");

    QImage image(photoName);


    //如果图片较大压缩图片大小
    if(image.width()>=3000||image.width()>=3000){
    int width = image.width() / 2;
    int height = image.height() / 2;
    image = image.scaled(width, height, Qt::KeepAspectRatio);
}

    //检测图像是否为空
    if(!image.isNull())
    {
        const string casPath = HAAR_PATH;

        //检测是否成功加载级联分类
        if (!cascade.load(casPath)) {
            qDebug() << "算法加载失败！";
            exit(-1);
        }

        //设置一个灰度图的Mat格式参数
        Mat imgGray;
        Mat tempMat(image.height(),image.width(),CV_8UC4,image.bits(),image.bytesPerLine());
        normalize(tempMat, tempMat, 0, 255, NORM_MINMAX, CV_8UC4);
        if (image.format() == QImage::Format_RGB888) {
            cvtColor(tempMat, tempMat, COLOR_RGB2BGR);
        }else {
            cvtColor(tempMat, tempMat, COLOR_BGRA2BGR);
        }

        QImage Qtempimag(tempMat.data, tempMat.cols, tempMat.rows, tempMat.step, QImage::Format_RGB888);

        //识别人脸并画框
        cvtColor(tempMat, imgGray, COLOR_BGR2GRAY);
        vector<Rect> faces(0);
        cascade.detectMultiScale(imgGray, faces, 1.1, 2, 0, Size(30, 30));  //调用人脸识别算法

        QString sNum = QString::number(faces.size());
        ui->numShow->setText(sNum); //输出人脸数

        if (faces.size() > 0) {
            for (size_t i = 0; i < faces.size(); i++) {
                rectangle(tempMat, faces[i], Scalar(0, 0, 255), 2, LINE_8);
            }
        }
        else {
            qDebug() << "No faces!";
        }


        int screenWidth = 1920;
        int screenHeight = 1080;

        //显示图像
        namedWindow("Face detection",WINDOW_NORMAL);
        setWindowProperty("Face detection", WND_PROP_FULLSCREEN, WINDOW_FULLSCREEN);
        resizeWindow("Face detection", Size(screenWidth, screenHeight));
        imshow("Face detection",tempMat);
        uchar c =waitKey(1);
        if(c == 13){
            //释放图像
            imgGray.release();
            tempMat.release();
            imgGray.release();
            tempMat.release();
            destroyWindow("Face detection");
            return;
        }


        }
}

//停止按钮，停止检测，清屏，可以进行图像识别
void videoDetect::on_stop_clicked()
{
    stop = true;
    ui->numShow->setText("");
    ui->origin->clear();
    ui->photo->setEnabled(true);

}

//退出按钮
void videoDetect::on_exit_clicked()
{
    exit(0);

}

//返回按钮，停止检测，清屏，可以进行图像识别，返回上一页面
void videoDetect::on_back_clicked()
{
    stop = true;
    ui->photo->setEnabled(true);
    ui->numShow->setText("");
    ui->origin->clear();
}
